package com.example.zhangxin.myhuatuob2b.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.convenientbanner.CBPageAdapter;
import com.bigkoo.convenientbanner.CBViewHolderCreator;
import com.bigkoo.convenientbanner.ConvenientBanner;
import com.example.zhangxin.myhuatuob2b.MyApplication;
import com.example.zhangxin.myhuatuob2b.R;
import com.example.zhangxin.myhuatuob2b.bean.GoodsInfo;
import com.example.zhangxin.myhuatuob2b.utils.URL;
import com.example.zhangxin.myhuatuob2b.view.LocalImageHolderView;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.Iterator;

public class GoodsDetailsActivity extends AppCompatActivity implements View.OnClickListener {

    private String goods_id;
    private ImageView imageBack;
    private LinearLayout sharekID;
    private ImageView isFavNoID;
    private ConvenientBanner banner;
    private LinearLayout activity_goods_details;
    private TextView goodsNameID;
    private TextView goodsJingleID;
    private TextView goodsPriceID;
    private TextView goods_mmarket_PriceID;
    private LinearLayout imageXingJiID;
    private TextView goodsSalenumID;
    private TextView goodsCollectID;
    private LinearLayout manSongViewID;
    private LinearLayout giftArrayViewID;
    private String mobile_body, goods_attr, textContent;
    private int upper_limit;
    private TextView tv_specNameID;
    private LinearLayout specNameID, specLinearLayoutID;
    private TextView cartNumID;
    private ImageView cartiID;
    private LinearLayout showCartLayoutID;
    private LinearLayout imID;
    private Button addCartID;
    private Button buyStepID;
    private String getLoginKey;
    private String member_role;
    private TextView goodsNumID;
    private Button numMinusID;
    private Button numPlusID;
    private int count = 1;
    private TextView goodsStorageID;
    private GoodsInfo bean;
    private String is_virtual;
    private String is_fcode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods_details);
        goods_id = getIntent().getStringExtra("goods_id");
        initView();
        initListener();
    }

    private void initListener() {
        specNameID.setOnClickListener(this);
        specLinearLayoutID.setOnClickListener(this);
    }

    private void initView() {

        imageBack = (ImageView) findViewById(R.id.imageBack);
        sharekID = (LinearLayout) findViewById(R.id.sharekID);
        isFavNoID = (ImageView) findViewById(R.id.isFavNoID);
        banner = (ConvenientBanner) findViewById(R.id.banner);
        activity_goods_details = (LinearLayout) findViewById(R.id.activity_goods_details);

        goodsNameID = (TextView) findViewById(R.id.goodsNameID);
        goodsJingleID = (TextView) findViewById(R.id.goodsJingleID);
        goodsPriceID = (TextView) findViewById(R.id.goodsPriceID);
        goods_mmarket_PriceID = (TextView) findViewById(R.id.goods_mmarket_PriceID);
        imageXingJiID = (LinearLayout) findViewById(R.id.imageXingJiID);
        goodsSalenumID = (TextView) findViewById(R.id.goodsSalenumID);
        goodsCollectID = (TextView) findViewById(R.id.goodsCollectID);
        manSongViewID = (LinearLayout) findViewById(R.id.manSongViewID);
        giftArrayViewID = (LinearLayout) findViewById(R.id.giftArrayViewID);
        goodsStorageID = (TextView) findViewById(R.id.goodsStorageID);

        loadingGoodsDetailsData();
        tv_specNameID = (TextView) findViewById(R.id.tv_specNameID);
        specNameID = (LinearLayout) findViewById(R.id.specnameid);
        specLinearLayoutID = (LinearLayout) findViewById(R.id.specLinearLayoutID);

        cartNumID = (TextView) findViewById(R.id.cartNumID);
        cartiID = (ImageView) findViewById(R.id.cartiID);
        showCartLayoutID = (LinearLayout) findViewById(R.id.showCartLayoutID);
        imID = (LinearLayout) findViewById(R.id.imID);

        addCartID = (Button) findViewById(R.id.addCartID);
        addCartID.setOnClickListener(this);
        buyStepID = (Button) findViewById(R.id.buyStepID);
        buyStepID.setOnClickListener(this);
        goodsNumID = (TextView) findViewById(R.id.goodsNumID);
        numMinusID = (Button) findViewById(R.id.numMinusID);
        numMinusID.setOnClickListener(this);
        numPlusID = (Button) findViewById(R.id.numPlusID);
        numPlusID.setOnClickListener(this);
    }

    private void loadingGoodsDetailsData() {
        String url = URL.URL_GOODSDETAILS + "&goods_id=" + goods_id + "&key=" + MyApplication.getLoginKey();
        RequestParams params = new RequestParams(url);

        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject object = new JSONObject(result);
                    JSONObject obj = object.getJSONObject("datas");
                    String goods_info = obj.getString("goods_info");
                    String is_favorate = obj.getString("is_favorate");// 是否已经收藏
                    String cart_count = obj.getString("cart_count");
                    System.out.println(cart_count);
                    goodsNumID.setText(count+"");
                    cartNumID.setText(cart_count == null ? "0" : cart_count);

                    bean = GoodsInfo.newInstanceList(goods_info);
                    goodsStorageID.setText("(当前库存" + (bean.getGoods_storage() == null ? "0" : bean.getGoods_storage()) + "盒)");

                    //是否是虚拟商品
                    is_virtual = bean.getIs_virtual() == null ? "0" : bean.getIs_virtual();

                    //是否是F吗商品
                    is_fcode = bean.getIs_fcode() == null ? "0" : bean.getIs_fcode();

                    if (is_favorate.equals("true")) {
                        isFavNoID.setBackgroundResource(R.mipmap.ic_star_metro_orang);
                    } else {
                        isFavNoID.setBackgroundResource(R.mipmap.ic_fav);
                    }

                    String specValue = "";
                    if (bean.getGoods_spec() != null && !bean.getGoods_spec().equals("") && !bean.getGoods_spec().equals("null")) {
                        JSONObject jsonGoods_spec = new JSONObject(bean.getGoods_spec());
                        Iterator<?> itName = jsonGoods_spec.keys();
                        while (itName.hasNext()) {
                            String specID = itName.next().toString();
                            String specV = jsonGoods_spec.getString(specID);
                            specValue += "," + specV;
                        }
                        tv_specNameID.setText("批号  " + specValue.replaceFirst(",", ""));
                    } else {
                        specNameID.setVisibility(View.GONE);
                    }

                    if (bean != null) {
                        setViewData(bean);
                    }
                    String goods_image = obj.getString("goods_image");
                    String[] strs = goods_image.split(",");
                    ArrayList<String> list = new ArrayList();
                    for (String s : strs
                            ) {
                        list.add(s);
                    }
                    if (list.size() > 0) {
                        banner.setVisibility(View.VISIBLE);
                        banner.setPages(new CBViewHolderCreator<CBPageAdapter.Holder>() {
                            @Override
                            public CBPageAdapter.Holder createHolder() {
                                return new LocalImageHolderView();
                            }
                        }, list).startTurning(2000).setPageIndicator(new int[]{R.drawable.dot1_shape, R.drawable.dot2_ahape}).setPointViewVisible(true);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private void setViewData(GoodsInfo bean) {
        mobile_body = bean.getMobile_body();
        goods_attr = bean.getGoods_attr();

        if (TextUtils.isEmpty(bean.getUpper_limit())) {
            upper_limit = Integer.parseInt((bean.getUpper_limit() == null ? "0" : bean.getUpper_limit()) == "" ? "0" : bean.getUpper_limit());
        }
        //显示商品名称
        goodsNameID.setText(bean.getGoods_name() == null ? "" : bean.getGoods_name());
//        specGoodsNameID.setText(bean.getGoods_name() == null ? "" : bean.getGoods_name());
        textContent = bean.getGoods_name();
        //判断是否显示商品说明
        if (bean.getGoods_jingle() != null && !bean.getGoods_jingle().equals("") && !bean.getGoods_jingle().equals("null")) {
            goodsJingleID.setVisibility(View.VISIBLE);
            goodsJingleID.setText(Html.fromHtml(bean.getGoods_jingle() == null ? "" : bean.getGoods_jingle()));
        } else {
            goodsJingleID.setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.specnameid:
                specLinearLayoutID.setVisibility(View.VISIBLE);
                break;
            case R.id.specLinearLayoutID:
                specLinearLayoutID.setVisibility(View.GONE);
                break;
            case R.id.addCartID:
                getLoginKey = MyApplication.getLoginKey();
                member_role  = MyApplication.getMember_role();
                if (getLoginKey.equals("")) {

                    Toast.makeText(this, "当前用户未登录！", Toast.LENGTH_LONG).show();

                    Intent intentToLogin = new Intent(this, LoginActivity.class);
                    startActivity(intentToLogin);

                } else {
                    shopAddCart();//添加购物车
                }
                break;
            case R.id.buyStepID:
                getLoginKey = MyApplication.getLoginKey();
                member_role  = MyApplication.getMember_role();

               if(TextUtils.isEmpty(getLoginKey)){
                   Toast.makeText(this, "当前用户未登录！", Toast.LENGTH_LONG).show();

                   startActivity(new Intent(this,LoginActivity.class));
               }else{
                   if(member_role.equals("0")){
                       Toast.makeText(this, "当前用户未认证！", Toast.LENGTH_LONG).show();
                   }else{
                       if(is_virtual.equals("1")){

                       }else{
                           Intent intent = new Intent(GoodsDetailsActivity.this, BuyStep1Activity.class);
                           intent.putExtra("is_fcode", is_fcode);
                           intent.putExtra("ifcart", "0");
                           intent.putExtra("cart_id", goods_id + "|" + Integer.parseInt(goodsNumID.getText().toString()));
                           startActivity(intent);
                       }
                   }
               }
                break;
            case R.id.numMinusID:
                count--;
                if(count<0){
                    count=0;
                }
                goodsNumID.setText(count+"");
                break;
            case R.id.numPlusID:
                count++;
                int max = Integer.parseInt(bean.getGoods_storage());
                if(count>max){
                    count = max;
                }
                goodsNumID.setText(count+"");
                break;
        }
    }

    private void shopAddCart() {
        String url = URL.URL_ADD_CART;

        RequestParams params = new RequestParams(url);
        params.addBodyParameter("goods_id", goods_id);
        params.addBodyParameter("key", MyApplication.getLoginKey());
        params.addBodyParameter("quantity", goodsNumID.getText().toString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                System.out.println("onSuccess>>>>>" + result);
                try {
                    JSONObject object = new JSONObject(result);
                    String flag = object.optString("datas");
                    if (flag.equals("1")) {
                        Toast.makeText(getApplicationContext(), "添加购物车成功", Toast.LENGTH_SHORT).show();
                        loadingGoodsDetailsData();
                    }
                    JSONObject obj = object.getJSONObject("datas");
                    if (!obj.isNull("error")) {

                        Toast.makeText(getApplicationContext(), obj.optString("error"), Toast.LENGTH_SHORT).show();
                        return;
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
}
